package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.LoginDto;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.UserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements UserService {

    /**
     * 用户登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        if (!StringUtils.isBlank(loginDto.getPhone()) && !StringUtils.isBlank(loginDto.getPassword())){
            //用户账号密码登录
            ApUser user = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            if (user == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"用户信息不存在");
            }
            //用户存在,密码对比
            String password = loginDto.getPassword();
            String salt = user.getSalt();
            //前端传回密码加上盐与数据库中的密码解码后对比
            if (!DigestUtils.md5DigestAsHex((password+salt).getBytes()).equals(user.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //密码正确,返回数据
            Map<String,Object> map = new HashMap<>();
            user.setPassword("");
            user.setSalt("");
            map.put("user",user);
            map.put("token", AppJwtUtil.getToken(user.getId().longValue()));
            return ResponseResult.okResult(map);
        }else {
            //游客登录
            Map<String,Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }
    }

    @Override
    public String getUserName(Integer userId) {

        ApUser apUser = this.getById(userId);
        String userName = apUser.getName();
        return userName;
    }
}
